package cn.org.gs.buffer;

import org.junit.Test;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

public class BufferDemo1 {

    @Test
    public void testBufferRead01() throws Exception{
        RandomAccessFile aFile = new RandomAccessFile("d:\\1.txt", "rw");

        FileChannel channel = aFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int read = channel.read(buffer);
        while (read != -1){
            buffer.flip();

            while (buffer.hasRemaining()){
                System.out.print((char) buffer.get());
            }
            buffer.clear();
            read = channel.read(buffer);
        }
        aFile.close();

    }

    @Test
    public void testBufferRead02() {
        IntBuffer buffer = IntBuffer.allocate(8);

        for (int i = 0; i < buffer.capacity(); i ++) {
            buffer.put(2 * (i + 1));
        }

        // limit在进行写数据时，数值与capacity一致，在进行读取数据时，limit值为数据的最大容量（not null）
        // 重置缓冲区，读取模式下，使用flip进行切换时，position会被置为0，之后从0开始读取数据
        buffer.flip();

        while (buffer.hasRemaining()) {
            System.out.print(buffer.get() + " ");
        }
    }
}
